<template>
  <el-table :data="localRecords" border class="chem-table" stripe table-layout="fixed">
    <el-table-column :index="indexMethod" align="center" label="序号" type="index" width="150" />

    <el-table-column align="center" label="取样日期" prop="sampleDate">
      <template #default="{ row }">
        <el-date-picker
          v-model="row.sampleDate"
          placeholder="选择日期"
          style="width: 100%"
          type="date"
          value-format="YYYY-MM-DD"
          @change="updateParent"
        />
      </template>
    </el-table-column>
    <el-table-column align="center" label="天气" prop="weather">
      <template #default="{ row }">
        <el-select
          v-model="row.weather"
          placeholder="选择天气"
          style="width: 100%"
          @change="updateParent"
        >
          <el-option label="晴天" value="晴天" />
          <el-option label="阴天" value="阴天" />
          <el-option label="雨天" value="雨天" />
        </el-select>
      </template>
    </el-table-column>
    <el-table-column align="center" label="气温(℃)" prop="temperature">
      <template #default="{ row }">
        <el-input v-model="row.temperature" placeholder="" @change="updateParent" />
      </template>
    </el-table-column>
    <el-table-column align="center" label="气压(kPa)" prop="airPressure">
      <template #default="{ row }">
        <el-input v-model="row.airPressure" placeholder="" @change="updateParent" />
      </template>
    </el-table-column>
    <el-table-column align="center" label="湿度(%RH)" prop="humidity">
      <template #default="{ row }">
        <el-input v-model="row.humidity" placeholder="" @change="updateParent" />
      </template>
    </el-table-column>
    <el-table-column align="center" label="操作" prop="humidity">
      <template #default="{ $index }">
        <el-button link type="primary" @click="addRow">新增</el-button>
        <el-button link type="primary" @click="removeRow($index)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
</template>

<script lang="ts" setup>
import { onMounted, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import dayjs from 'dayjs'
import { ElMessage } from 'element-plus'

const route = useRoute()
const router = useRouter()
const day = ref(1)
// 从父组件接受天气信息
const props = defineProps<{
  weatherRecords: WeatherRecord[]
}>()

// 调用父组件方法修改天气信息
const emit = defineEmits<{
  (e: 'update-records', records: WeatherRecord[]): void
}>()

// 创建本地副本以避免直接修改 props
const localRecords = ref<WeatherRecord[]>([])

// 初始化时复制 props 到本地状态，判断如何天气长度为1并且检测日期为空的额时候默认是当天
watch(
  () => props.weatherRecords,
  (newVal) => {
    console.log('天气组件', JSON.stringify(newVal))
    localRecords.value = JSON.parse(JSON.stringify(newVal))
  },
  { immediate: true }
)

const updateParent = () => {
  emit('update-records', localRecords.value)
}

interface WeatherRecord {
  id: string
  sampleDate: string
  temperature: string
  airPressure: string
  humidity: string
  weather: string
}

const addRow = () => {
  if (localRecords.value.length === 0) {
    // 如果数组为空，添加第一条记录
    localRecords.value.push({
      id: '',
      sampleDate: dayjs().format('YYYY-MM-DD'),
      temperature: '',
      airPressure: '',
      weather: '',
      humidity: ''
    })

    return
  }

  // 获取最后一条记录的日期
  const lastRecord = localRecords.value[localRecords.value.length - 1]
  const lastDate = lastRecord.sampleDate

  // 计算新日期（最后日期+1天）
  const newDate = dayjs(lastDate).add(1, 'day').format('YYYY-MM-DD')

  localRecords.value.push({
    id: '',
    sampleDate: newDate,
    temperature: '',
    airPressure: '',
    weather: '',
    humidity: ''
  })
  updateParent()
}

const removeRow = (index) => {
  if (localRecords.value.length == 1) {
    ElMessage.warning('请至少保留一条记录')
    return
  }
  localRecords.value.splice(index, 1)
  updateParent()
}
const indexMethod = (index: number) => {
  return `第${day.value + index}天`
}

onMounted(() => {})

// 校验本表单必填项不为空；供父组件调用
const validateRequired = (): boolean => {
  const fieldLabels: Record<keyof WeatherRecord, string> = {
    id: 'ID',
    sampleDate: '取样日期',
    temperature: '气温',
    airPressure: '气压',
    humidity: '湿度',
    weather: '天气'
  }

  for (let i = 0; i < localRecords.value.length; i++) {
    const record = localRecords.value[i]
    const emptyFields: string[] = []

    if (!record.sampleDate) emptyFields.push(fieldLabels.sampleDate)
    if (!record.weather) emptyFields.push(fieldLabels.weather)
    if (record.temperature === '') emptyFields.push(fieldLabels.temperature)
    if (record.airPressure === '') emptyFields.push(fieldLabels.airPressure)
    if (record.humidity === '') emptyFields.push(fieldLabels.humidity)

    if (emptyFields.length > 0) {
      ElMessage.warning(`气象记录—中第${i + 1}行未填写：${emptyFields.join('、')}`)
      return false
    }
  }
  return true
}

defineExpose({ validateRequired })
</script>

<style lang="scss" scoped>
.el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}

.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}

.chem-form {
  background: none;
  box-shadow: none;
  border-radius: 0;
  margin-bottom: 0;

  :deep(.el-input__inner) {
    border-radius: 0 !important;
    box-shadow: none !important;
  }

  :deep(.el-form-item__label) {
    white-space: nowrap;
  }
}

.chem-btns {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  align-items: center;
  margin-top: 0;
}

.chem-table {
  margin-top: 18px;
  --el-table-border-radius: 0 !important;
  --el-table-header-bg-color: #f7f8fa;
  --el-table-border-color: #e5e6eb;
  box-shadow: none !important;
  border-radius: 0 !important;

  :deep(.el-table__header th) {
    background: #f7f8fa !important;
    font-weight: 600;
    font-size: 14px;
    border-radius: 0 !important;
    padding: 8px 0 !important;

    .cell {
      padding-left: 0px !important;
      padding-right: 0px !important;
    }
  }

  // 设置表格行高
  :deep(.el-table__body td) {
    border-radius: 0 !important;

    font-size: 14px;
    padding: 0 !important;
    // 列和单元格的边距
    .cell {
      padding: 0px 0px;
    }
  }

  // 去掉输入框边框
  :deep(.el-input__wrapper) {
    border-radius: 0 !important;
    box-shadow: none !important;
  }

  // 针对下拉选择框的所有相关元素去掉边框
  :deep(.el-select__wrapper) {
    border: none !important;
    box-shadow: none !important;
  }
}

.input-with-unit {
  position: relative;
}

:deep(.el-input__inner) {
  text-align: center;
}

.unit-text {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  color: #909399;
  font-size: 14px;
  pointer-events: none;
  z-index: 1;
}
</style>
